/*
 * All rights Reserved, Designed By cloudland Copyright(C) 2010-2014
 *
 * fileName:  HttpNetwork.java
 * author:  lei
 * Company:  Cloudland Studio
 * Createdate:  2013-9-15 下午2:24:43
 *   
 * Modification  History:
 *     Date           Author        Version        
 * -------------------------------------------
 * 2013-9-15          Lei            1.0        
 *
 * Why & What is modified:
 * 1.0: 文件创建
 */
package org.cloudland.network;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

 /**
 * <pre> 
 * HTTP 协议访问服务。
 * </pre>
 * @ClassName  HttpNetwork
 * @author  lei
 * @version  %I%, %G%
 * @see  
 * @since   JDK1.6
 *
 */
public class HttpNetwork {

	/**
     * HTTP_CLIENT Http客户端对象
     */
    private static HttpClient HTTP_CLIENT = new DefaultHttpClient();
    
    /**
     * client HTTP 请求对象
     */
    private HttpRequestBase client = null;
    
    /**
     * CAHR_SET 默认编码
     */
    private String CAHR_SET = "UTF-8";
    
    /** 
     * default constructor
     */
    private HttpNetwork(String uri, boolean isPost){
        if (isPost) {
            client = new HttpPost(uri);
        } else {
            client = new HttpGet(uri);
        }
    }
    
    /** 
     * doPost 构建 Post 方式的 HTTP 通信对象
     *
     * @param url 请求地址
     * @return 以 Post 方式请求的 HTTP 通信对象
     */
    public static HttpNetwork doPost(String url) {
        return new HttpNetwork(url, true);
    }
    
    /** 
     * doGet 构建 Get 方式的 HTTP 通信对象
     *
     * @param url 请求地址
     * @return 以 Get 方式请求的 HTTP 通信对象
     */
    public static HttpNetwork doGet(String url) {
        return new HttpNetwork(url, false);
    }
    
    /** 
     * addHeader 添加 HTTP 请求头信息
     *
     * @param name 名称
     * @param value 变量
     */
    public void addHeader(String name, String value) {
        client.addHeader(name, value);
    }
    
    
    /** 
     * doRequest 执行请求
     *
     * @param entity 请求参数对象
     * @return 响应结果
     */
    private String doRequest(HttpEntity entity) {
        
        // 根据请求类型处理请求参数
        if (client.getMethod().equals(HttpPost.METHOD_NAME)) {
            ((HttpPost)client).setEntity(entity);
        } else if (client.getMethod().equals(HttpGet.METHOD_NAME)) {
            String getParams = null;
            try
            {
                getParams = EntityUtils.toString(entity);
            }
            catch (ParseException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            catch (IOException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
            StringBuffer buffURI = new StringBuffer(client.getURI().toString()).append("?");
            buffURI.append(getParams);
            client.setURI(URI.create(buffURI.toString()));
        }
        
        String respConetnt = null;
        try {
            client.getParams().setParameter(HttpHeaders.CONTENT_ENCODING, CAHR_SET);
            client.addHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
            HttpResponse resp = HTTP_CLIENT.execute(client);
            respConetnt = EntityUtils.toString(resp.getEntity());
        } catch (ClientProtocolException e) {
            // TODO 客户端协议异常
            e.printStackTrace();
        } catch (IOException e) {
            // TODO 访问或读取异常
            e.printStackTrace();
        } finally {
            HTTP_CLIENT.getConnectionManager().shutdown();
        }
        
        return respConetnt;
        
    }
    
    public String execute(String content) {
        
        String respConetnt = null;
        try
        {
            HttpEntity entity = new StringEntity(content, CAHR_SET);
            respConetnt = doRequest(entity);
        }
        catch (UnsupportedEncodingException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        if (null == respConetnt || respConetnt.length() <= 0) {
            return null;
        }
        //respConetnt = execute0(entity);
        
        return respConetnt;
    }
    
       
    public String execute(Map<String, String> params) {
        
        HttpEntity entity = null;
        if (null != params) {
            List<NameValuePair> array = new ArrayList<NameValuePair>(params.size());
            NameValuePair pair = null;
            for (Entry<String, String> en : params.entrySet()) {
                pair = new BasicNameValuePair(en.getKey(), en.getValue());
                array.add(pair);
            }
            
            try {
                entity = new StringEntity(URLEncodedUtils.format(array, CAHR_SET), CAHR_SET);
                //entity = new UrlEncodedFormEntity(array);
                //getParams = EntityUtils.toString(entity);
            } catch (UnsupportedEncodingException e) {
                // TODO 组装请求数据错误
                e.printStackTrace();
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
        }
        
        String respConetnt = doRequest(entity);
        
        //respConetnt = execute0(entity);
        
        return respConetnt;
    }
}
